package com.tang.controller;

import com.tang.entity.Admin;
import com.tang.entity.Reader;

import com.tang.service.LoginService;

import com.tang.service.impl.LoginServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author tang
 * @create 2020-08-16
 */


@WebServlet("/login")
/**
 * 接收并响应登录请求
 */
public class LoginServlet extends HttpServlet {

    private LoginService loginService =  new LoginServiceImpl();

    /**
     * 区分读者与管理员，转向两者登录首页
     * @param req
     * @param resp
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String username =  req.getParameter("username");
        String password =  req.getParameter("password");
        String type =  req.getParameter("type");
        Object object = loginService.login(username,password,type);

        if (object!=null){
            HttpSession session =  req.getSession();
            switch (type){
                case "reader":
                    Reader reader = (Reader) object;
                    session.setAttribute("reader",reader);
                    resp.sendRedirect("/reader?page=1");
                    break;

                case "admin":
                    Admin admin = (Admin) object;
                    session.setAttribute("admin",admin);
                    resp.sendRedirect("/admin?method=review");
                    break;
            }
        }
        else {
              resp.sendRedirect("login.jsp");
        }
    }
}
